package com.example.music.controller;

import com.example.music.common.ServerResponse;
import com.example.music.domain.*;
import com.example.music.service.UserService;
import com.example.music.util.EmptyUtil;
import com.example.music.util.FileUploadAndDownload;
import com.example.music.util.PropertiesUtils;
import com.example.music.util.VideoUtil;
import com.example.music.util.excel.ExcelUtils;
import com.example.music.util.jwt.JwtUtil;
import com.example.music.util.redis.RedisUtil;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;



@CrossOrigin
@Controller
@RequestMapping(value = "/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserService userService;

    @Autowired
    public RedisUtil redisUtil;


    private static String path = PropertiesUtils.getProperties();


    private static String netPath = PropertiesUtils.getNetProperties();


    /**
     * 获取角色身份
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRole", method = RequestMethod.GET)
    public ServerResponse<List<Role>> getRole() {
        List<Role> roleList = userService.getRole();
        return ServerResponse.createBySuccess(roleList);
    }


    /**
     * 用户登录（返回类）
     *
     * @param user（loginName，password，roleId）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ServerResponse<String> login(@RequestBody User user) {
        logger.info("登录" + user);
        User loginUser = userService.login(user);
        if (EmptyUtil.isNotEmpty(loginUser)) {
//            loginUser.setLoginTime(System.currentTimeMillis());
//            loginUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);//置空密码
            loginUser.setHeadPortrait(netPath + loginUser.getHeadPortrait());
            // todo important token有效期10个小时
            String token = JwtUtil.sign(loginUser, 600000L * 1000L * 6L);//token有效期10小时
            return ServerResponse.createBySuccess(token);
        } else {
            return ServerResponse.createByErrorMsg("账号名或者密码输入错误");
        }
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ServerResponse<String> register(@RequestBody User user) {
        logger.info("注册用户" + user);
        return userService.register(user);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = new JSONObject(email);
        logger.info("email" + jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.generateCheckCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forgetCheckCode", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(@RequestBody String email) {
        JSONObject jsonObj = new JSONObject(email);
        logger.info("email" + jsonObj.getString("email"));
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(jsonObj.getString("email"));
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody User user) {
        return userService.updatePassword(user);
    }

    /**
     * 游客登录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "expertLogin", method = RequestMethod.POST)
    public ServerResponse<String> expertLogin() {
        User expertLoginUser = new User();
        expertLoginUser.setRoleId(4);
        expertLoginUser.setUsername("评审账户");
        expertLoginUser.setLoginName("pszh" + System.currentTimeMillis());
        expertLoginUser.setPassword("mima" + System.currentTimeMillis());
//        expertLoginUser.setLoginTime(System.currentTimeMillis());
        expertLoginUser.setHeadPortrait(netPath + "touxiang.jpg");
        userService.expertLogin(expertLoginUser);
        logger.info("用户信息" + expertLoginUser);
        String token = JwtUtil.sign(expertLoginUser, 6000L * 1000L * 6L);//token有效期60分钟
        return ServerResponse.createBySuccess(token);
    }


    /**
     * 管理员搜索用户+查看用户
     *
     * @param request
     * @param searchUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUser", method = RequestMethod.POST)
    public ServerResponse<PageInfo> searchUser(HttpServletRequest request, @RequestBody String searchUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(searchUser);
        Integer pageSize = jsonObject.getInt("pageSize");
        Integer pageNum = jsonObject.getInt("pageNum");
        String username = jsonObject.getString("username");
        return userService.searchUser(pageNum, pageSize, username);
    }

    /**
     * 删除用户
     *
     * @param request
     * @param deleteUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public ServerResponse deleteUser(HttpServletRequest request, @RequestBody String deleteUser) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(deleteUser);
        Integer id = jsonObject.getInt("id");
        return userService.deleteUser(id);
    }


    /**
     * 用户修改个人头像
     *
     * @param request
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateHeadPortrait", method = RequestMethod.POST)
    public ServerResponse updateHeadPortrait(HttpServletRequest request, MultipartFile file) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        String headPortrait = fileUploadAndDownload.uploadTouXiang(file);
        return userService.updateHeadPortrait(u.getId(), headPortrait, u);
    }


    /**
     * 获取到首页数据
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getIndexSong", method = RequestMethod.POST)
    public ServerResponse getIndexSong(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.getIndexSong();
    }


    /**
     * 上传歌曲信息
     *
     * @param request
     * @param songName           歌曲名称
     * @param songKind           歌曲类型
     * @param songIntroduce      歌曲介绍
     * @param songOriginalSinger 原唱作者
     * @param songAccompany      伴奏
     * @param songOriginal       原唱
     * @param songPicture        歌曲图片
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadSong", method = RequestMethod.POST)
    public ServerResponse uploadSong(HttpServletRequest request, String songName, Integer songKind, String songIntroduce, String songOriginalSinger, MultipartFile songAccompany, MultipartFile songOriginal, MultipartFile songPicture,MultipartFile file,MultipartFile songVoiceFile,MultipartFile musicFile) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        Song song = new Song();
        song.setSongName(songName);
        song.setSongKind(songKind);
        song.setSongIntroduce(songIntroduce);
        song.setSongOriginalSinger(songOriginalSinger);
//        song.setSongLyric(songLyric);
        song.setUId(u.getId());
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        String songAccompanyFileName = songAccompany.getOriginalFilename();
        String songAccompanySuffixName = songAccompanyFileName.substring(songAccompanyFileName.lastIndexOf(".") + 1);
        if (!"mp3".equalsIgnoreCase(songAccompanySuffixName)) {
            return ServerResponse.createByErrorMsg("上传的伴奏的文件格式必须是mp3格式！");
        }
        song.setSongAccompanyFileName(songAccompanyFileName);
        String songOriginalFileName = songOriginal.getOriginalFilename();
        String songOriginalSuffixName = songOriginalFileName.substring(songOriginalFileName.lastIndexOf(".") + 1);
        if (!"mp3".equalsIgnoreCase(songOriginalSuffixName)) {
            return ServerResponse.createByErrorMsg("上传的原唱的文件格式必须是mp3格式！");
        }
        song.setSongOriginalFileName(songOriginalFileName);
        String songPictureFileName = songPicture.getOriginalFilename();
        String songPictureSuffixName = songPictureFileName.substring(songPictureFileName.lastIndexOf(".") + 1);
        if (!"jpg".equalsIgnoreCase(songPictureSuffixName) && !"png".equalsIgnoreCase(songPictureSuffixName)) {
            return ServerResponse.createByErrorMsg("上传的歌曲图片格式必须是jpg或者是png");
        }
        String musicPictureFileName=musicFile.getOriginalFilename();
        String musicPictureSuffixName=musicPictureFileName.substring(musicPictureFileName.lastIndexOf(".")+1);
        if (!"jpg".equalsIgnoreCase(musicPictureSuffixName) && !"png".equalsIgnoreCase(musicPictureSuffixName)) {
            return ServerResponse.createByErrorMsg("上传的乐谱图片格式必须是jpg或者是png");
        }
        try {
            String songAccompanyPath = fileUploadAndDownload.upload(songAccompany);
            song.setSongAccompany(songAccompanyPath);
            logger.info("{}成功上传伴奏", u.getUsername());
        } catch (Exception e) {
            logger.info("{}上传图片伴奏", u.getUsername());
        }

        try {
            String musicPath = fileUploadAndDownload.upload(musicFile);
            song.setMusic(musicPath);
            logger.info("{}成功上传乐谱图片", u.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("{}上传乐谱图片伴奏", u.getUsername());
        }
        try {
            String songOriginalPath = fileUploadAndDownload.upload(songOriginal);
            song.setSongOriginal(songOriginalPath);
            String songDuration = VideoUtil.getVedioTime(new File(path + songOriginalPath));
            song.setSongDuration(songDuration);
            logger.info("{}成功上传原唱歌曲", u.getUsername());
        } catch (Exception e) {
            logger.info("{}上传原唱歌曲失败", u.getUsername());
        }
        try {
            String songPicturePath = fileUploadAndDownload.upload(songPicture);
            song.setSongPicture(songPicturePath);
            logger.info("{}成功上传图片", u.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("{}上传图片失败", u.getUsername());
        }
        logger.info("上传的数据{}", song);

        String songVoiceFileName = songVoiceFile.getOriginalFilename();
        String songVoiceSuffixName = songVoiceFileName.substring(songVoiceFileName.lastIndexOf(".") + 1);
        if (!"mp3".equalsIgnoreCase(songVoiceSuffixName)) {
            return ServerResponse.createByErrorMsg("上传的人声的文件格式必须是mp3格式！");
        }
        try {
            String songVoicePath = fileUploadAndDownload.upload(songVoiceFile);
            song.setSongVoice(songVoicePath);
            song.setVoiceName(songVoiceFileName);
            logger.info("{}成功上传人声歌曲", u.getUsername());
        } catch (Exception e) {
            logger.info("{}上传人声歌曲失败", u.getUsername());
        }

        String excelFileName = file.getOriginalFilename();
        String excelFileSuffixName = excelFileName.substring(excelFileName.lastIndexOf(".") + 1);
        if (!("xlsx".equalsIgnoreCase(excelFileSuffixName)||"xls".equalsIgnoreCase(excelFileSuffixName))) {
            return ServerResponse.createByErrorMsg("上传的歌曲时间段歌词的文件格式必须是xls或者xlsx格式！");
        }
        List<Lyrics> lyricsList = new ArrayList<>();
// 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        try {
            File tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, Lyrics.class);
            if (objectList == null) {
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    Lyrics lyrics = (Lyrics) objectList.get(i);
                    if(!StringUtils.isEmpty(lyrics.getLyricDate())){
                        String[] lyricDateArray=lyrics.getLyricDate().split(":");
                        for (String lyricDate : lyricDateArray) {
                            try {
                                Integer lyricDateInt=Integer.parseInt(lyricDate);
                            }catch (Exception e){
                                return ServerResponse.createByErrorMsg("上传歌曲时间阶段格式有问题！");
                            }
                        }
                        lyricsList.add(lyrics);
                    }
                }
            }
            song.setSongLyricsName(excelFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userService.uploadSong(song,lyricsList);
    }


    /**
     * 获取歌曲信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSong", method = RequestMethod.POST)
    public ServerResponse getSong(HttpServletRequest request, @RequestBody String getSong) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(getSong);
        return userService.getSong(u, jsonObject);
    }

    /**
     * 根据歌曲编号来获取到歌曲的所有信息
     *
     * @param request
     * @param getSongById
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSongById", method = RequestMethod.POST)
    public ServerResponse getSongById(HttpServletRequest request, @RequestBody String getSongById) {
        JSONObject jsonObject = new JSONObject(getSongById);
        Integer songId = jsonObject.getInt("songId");
        return userService.getSongById(songId);
    }


    /**
     * 获取到音乐类型
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSongKind", method = RequestMethod.POST)
    public ServerResponse getSongKind(HttpServletRequest request) {
        return userService.getSongKind();
    }


    /**
     * 根据上传音乐类型获取到音乐的全部信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSongByKind", method = RequestMethod.POST)
    public ServerResponse getSongByKind(HttpServletRequest request, @RequestBody String getSongKind) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(getSongKind);
        Integer kindId = jsonObject.getInt("kindId");
        Integer pageNum = jsonObject.getInt("pageNum");
        Integer pageSize = jsonObject.getInt("pageSize");
        String keyword = jsonObject.getString("keyword");
        return userService.getSongByKind(kindId, pageNum, pageSize, keyword, u);
    }


    /**
     * U3d请求访问后端接口,请求格式为:Json
     *
     * @param songInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getU3dSongInfo", method = RequestMethod.POST)
    public ServerResponse getU3dSongInfo(@RequestBody String songInfo) {
        JSONObject jsonObject = new JSONObject(songInfo);
        String token = jsonObject.getString("token");
        Integer songId = jsonObject.getInt("songId");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        User loginUser = userService.loginUser(u);//用用户角色编号和用户名来查询
        u.setHeadPortrait(loginUser.getHeadPortrait());
        U3DSong u3DSong = userService.getU3dSongInfo(songId);
        u3DSong.setUsername(loginUser.getUsername());
        u3DSong.setMusic(netPath+u3DSong.getMusic());
        u3DSong.setSongAccompany(netPath + u3DSong.getSongAccompany());
        u3DSong.setSongPicture(netPath + u3DSong.getSongPicture());
        u3DSong.setSongOriginal(netPath + u3DSong.getSongOriginal());
        u3DSong.setSongVoice(netPath+u3DSong.getSongVoice());
        u3DSong.setHeadPortrait(netPath + loginUser.getHeadPortrait());
        Integer duration = 0;
        if (!StringUtils.isEmpty(u3DSong.getSongDuration())) {
            String[] durationArray = u3DSong.getSongDuration().split(":");
            Integer second = 60;
            if (durationArray.length != 0) {
                if (durationArray.length == 3) {
                    second = second * 60;
                }
                for (int i = 0; i < durationArray.length; i++) {
                    duration += second * Integer.parseInt(durationArray[i]);
                    second = second / 60;
                }
            }
        }
        u3DSong.setSongDuration(duration + "");
        List<U3DLyrics> lyricsList = userService.getLyrics(songId);
        lyricsList.forEach(u3DLyrics -> {
            Integer second2 = 60;
            Integer lyricDate = 0;
            if (!StringUtils.isEmpty(u3DLyrics.getLyricDate())) {
                String[] lyricDateArray = u3DLyrics.getLyricDate().split(":");
                if (lyricDateArray.length == 3) {
                    second2 = second2 * 60;
                }
                for (int i = 0; i < lyricDateArray.length; i++) {
                    lyricDate += second2 * Integer.parseInt(lyricDateArray[i]);
                    second2 = second2 / 60;
                }
            }
            u3DLyrics.setLyricDate(lyricDate + "");
        });
        u3DSong.setLyricsList(lyricsList);
        return ServerResponse.createBySuccess(u3DSong);
    }


    /**
     * U3D调用后端伴奏原唱声音合成
     * @param songId
     * @param token
     * @param file
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "getU3dByValue",method = RequestMethod.POST)
//    public ServerResponse getU3dByValue(Integer songId,String token,MultipartFile file){
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
//        FileUploadAndDownload fileUploadAndDownload=new FileUploadAndDownload();
//        String selfSinging=fileUploadAndDownload.upload(file);
//        return userService.getU3dByValue(songId,u,selfSinging);
//    }


    /**
     * U3D调用后端伴奏原唱声音合成
     *
     * @param songId
     * @param token
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getU3dByValue", method = RequestMethod.POST)
    public ServerResponse getU3dByValue(Integer songId, String token, MultipartFile file) {
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        String path = fileUploadAndDownload.upload(file);
        return userService.getU3dByValue(songId, path, u);
    }


    /**
     * 获取到用户唱完的歌曲
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserReportSong", method = RequestMethod.POST)
    public ServerResponse getUserReportSong(HttpServletRequest request, @RequestBody String getUserReportSong) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(getUserReportSong);
        Integer pageNum = jsonObject.getInt("pageNum");
        Integer pageSize = jsonObject.getInt("pageSize");
        String keyword = jsonObject.getString("keyword");
//        User u=new User();
//        u.setId(1);
        return userService.getUserReportSong(u.getId(), pageNum, pageSize, keyword);
    }

    /**
     * 根据歌曲报告编号来删除歌曲
     *
     * @param request
     * @param delUserReportSong
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delUserReportSong", method = RequestMethod.POST)
    public ServerResponse delUserReportSong(HttpServletRequest request, @RequestBody String delUserReportSong) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(delUserReportSong);
        Integer reportId = jsonObject.getInt("reportId");
        return userService.delUserReportSong(reportId);
    }


    /**
     * 根据用户歌曲报告编号来下载
     *
     * @param reportId
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/downloadReportSong", method = RequestMethod.GET)
    public ServerResponse downloadReportSong(String token, Integer reportId, HttpServletRequest request, HttpServletResponse response) {
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String selfSinging = path + userService.downloadReportSong(reportId);
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        fileUploadAndDownload.download(request, response, selfSinging);
        return null;
    }

    /**
     * 下载上传的原唱歌曲
     *
     * @param token
     * @param songId
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/downloadOriginSong", method = RequestMethod.GET)
    public ServerResponse downloadOriginSong(String token, Integer songId, HttpServletRequest request, HttpServletResponse response) {
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String songPath = path + userService.downloadOriginSong(songId);
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        fileUploadAndDownload.download(request, response, songPath);
        return null;

    }


    /**
     * 修改歌曲（是否公开）
     *
     * @param request
     * @param changePublicity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePublicity", method = RequestMethod.POST)
    public ServerResponse changePublicity(HttpServletRequest request, @RequestBody String changePublicity) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(changePublicity);
        Integer reportId = jsonObject.getInt("reportId");
        boolean publicity = jsonObject.getBoolean("publicity");
        return userService.changePublicity(reportId, publicity);
    }

    /**
     * 用户获取动态信息
     *
     * @param
     * @param getReportDynamic
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getReportDynamic", method = RequestMethod.POST)
    public ServerResponse getReportDynamic(HttpServletRequest request, @RequestBody String getReportDynamic) {
        String token = request.getHeader("Authorization");
        Integer uid = null;
        Integer roleId = 1;
        if (!StringUtils.isEmpty(token)) {
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            uid = u.getId();
            roleId = u.getRoleId();
        }
        JSONObject jsonObject = new JSONObject(getReportDynamic);
        Integer pageNum = jsonObject.getInt("pageNum");
        Integer pageSize = jsonObject.getInt("pageSize");
        String keyword = jsonObject.getString("keyword");
        return userService.getReportDynamic(pageNum, pageSize, keyword, uid, roleId);
    }


    /**
     * u3d提交数据
     *
     * @param report
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/u3dInsertReport", method = RequestMethod.POST)
    public ServerResponse u3dInsertReport(@RequestBody Report report) {
        return userService.u3dInsertReport(report);
    }


    /**
     * 用户根据歌曲编号来删除用户自己上传的伴奏资料
     *
     * @param request
     * @param delSong
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delSong", method = RequestMethod.POST)
    public ServerResponse delSong(HttpServletRequest request, @RequestBody String delSong) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(delSong);
        Integer songId = jsonObject.getInt("songId");
        return userService.delSong(songId);
    }


    /**
     * 获取用户实验报告（公开的）
     *
     * @param request
     * @param getExperimentReport
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getExperimentReport", method = RequestMethod.POST)
    public ServerResponse getExperimentReport(HttpServletRequest request, @RequestBody String getExperimentReport) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = new JSONObject(getExperimentReport);
        Integer pageNum = jsonObject.getInt("pageNum");
        Integer pageSize = jsonObject.getInt("pageSize");
        String keyword = jsonObject.getString("keyword");
        return userService.getExperimentReport(u, pageNum, pageSize, keyword);
    }


    /**
     * 根据歌曲编号来修改歌曲信息
     *
     * @param request
     * @param songId             歌曲编号
     * @param songName           歌曲名称
     * @param songKind           歌曲类型
     * @param songIntroduce      歌曲介绍
     * @param songAccompany      歌曲伴奏
     * @param songOriginal       歌曲原唱
     * @param songPicture        歌曲背景
     * @param songOriginalSinger 歌曲原唱作者
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateSong", method = RequestMethod.POST)
    public ServerResponse updateSong(HttpServletRequest request, Integer songId, String songName, Integer songKind, String songIntroduce, String songOriginalSinger, MultipartFile songAccompany, MultipartFile songOriginal, MultipartFile songPicture,MultipartFile file,MultipartFile songVoiceFile,MultipartFile musicFile) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        Song song = new Song();
        song.setSongId(songId);
        song.setSongName(songName);
        song.setSongKind(songKind);
        song.setSongIntroduce(songIntroduce);
        song.setSongOriginalSinger(songOriginalSinger);
        FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
        if (songAccompany != null) {
            String songAccompanyFileName = songAccompany.getOriginalFilename();
            String songAccompanySuffixName = songAccompanyFileName.substring(songAccompanyFileName.lastIndexOf(".") + 1);
            if (!"mp3".equalsIgnoreCase(songAccompanySuffixName)) {
                return ServerResponse.createByErrorMsg("上传的伴奏的文件格式必须是mp3格式！");
            }
            String songAccompanyPath = fileUploadAndDownload.upload(songAccompany);
            song.setSongAccompany(songAccompanyPath);
            song.setSongAccompanyFileName(songAccompanyFileName);
        }
        if (songOriginal != null) {
            String songOriginalFileName = songOriginal.getOriginalFilename();
            String songOriginalSuffixName = songOriginalFileName.substring(songOriginalFileName.lastIndexOf(".") + 1);
            if (!"mp3".equalsIgnoreCase(songOriginalSuffixName)) {
                return ServerResponse.createByErrorMsg("上传的原唱的文件格式必须是mp3格式！");
            }
            String songOriginalPath = fileUploadAndDownload.upload(songOriginal);
            String songDuration = VideoUtil.getVedioTime(new File(path + songOriginalPath));
            song.setSongDuration(songDuration);
            song.setSongOriginal(songOriginalPath);
            song.setSongOriginalFileName(songOriginalFileName);
        }
        if (songPicture != null) {
            String songPictureFileName = songPicture.getOriginalFilename();
            String songPictureSuffixName = songPictureFileName.substring(songPictureFileName.lastIndexOf(".") + 1);
            if (!"jpg".equalsIgnoreCase(songPictureSuffixName) && !"png".equalsIgnoreCase(songPictureSuffixName)) {
                return ServerResponse.createByErrorMsg("上传的歌曲图片格式必须是jpg或者是png");
            }
            String songPicturePath = fileUploadAndDownload.upload(songPicture);
            song.setSongPicture(songPicturePath);
        }
        if(songVoiceFile!=null){
            String songVoiceFileName = songVoiceFile.getOriginalFilename();
            String songVoiceSuffixName = songVoiceFileName.substring(songVoiceFileName.lastIndexOf(".") + 1);
            if (!"mp3".equalsIgnoreCase(songVoiceSuffixName)) {
                return ServerResponse.createByErrorMsg("上传的人声的文件格式必须是mp3格式！");
            }
            try {
                String songVoicePath = fileUploadAndDownload.upload(songVoiceFile);
                song.setSongVoice(songVoicePath);
                song.setVoiceName(songVoiceFileName);
                logger.info("{}成功上传人声歌曲", u.getUsername());
            } catch (Exception e) {
                logger.info("{}上传人声歌曲失败", u.getUsername());
            }
        }

        if(null!=musicFile){
            String musicPictureFileName=musicFile.getOriginalFilename();
            String musicPictureSuffixName=musicPictureFileName.substring(musicPictureFileName.lastIndexOf(".")+1);
            if (!"jpg".equalsIgnoreCase(musicPictureSuffixName) && !"png".equalsIgnoreCase(musicPictureSuffixName)) {
                return ServerResponse.createByErrorMsg("上传的乐谱图片格式必须是jpg或者是png");
            }
            try {
                String musicPath = fileUploadAndDownload.upload(musicFile);
                song.setMusic(musicPath);
                logger.info("{}成功上传乐谱图片", u.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("{}上传乐谱图片伴奏", u.getUsername());
            }
        }
        List<Lyrics> lyricsList = new ArrayList<>();
        if(file!=null){
            String excelFileName = file.getOriginalFilename();
            String excelFileSuffixName = excelFileName.substring(excelFileName.lastIndexOf(".") + 1);
            if (!("xlsx".equalsIgnoreCase(excelFileSuffixName)||"xls".equalsIgnoreCase(excelFileSuffixName))) {
                return ServerResponse.createByErrorMsg("上传的歌曲时间段歌词的文件格式必须是xls或者xlsx格式！");
            }
// 获取文件名
            String fileName = file.getOriginalFilename();
            logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            logger.info("文件的后缀名为：" + suffixName);
            //创建一个临时文件，用于暂时存放
            try {
                File tmpFile = File.createTempFile("tmp", null);
                //将MultipartFile 转换为 File 临时文件
                file.transferTo(tmpFile);
                //将临时文件转为输入流
                InputStream inputStream = new FileInputStream(tmpFile);
                List<Object> objectList = ExcelUtils.readExcel(inputStream, Lyrics.class);
                if (objectList == null) {
                    return ServerResponse.createByErrorMsg("数据有误，上传失败");
                } else if (EmptyUtil.isEmpty(objectList)) {
                    return ServerResponse.createByErrorMsg("数据为空");
                } else {
                    for (int i = 0; i < objectList.size(); i++) {
                        Lyrics lyrics = (Lyrics) objectList.get(i);
                        if(!StringUtils.isEmpty(lyrics.getLyricDate())){
                            String[] lyricDateArray=lyrics.getLyricDate().split(":");
                            for (String lyricDate : lyricDateArray) {
                                try {
                                    Integer lyricDateInt=Integer.parseInt(lyricDate);
                                }catch (Exception e){
                                    return ServerResponse.createByErrorMsg("上传歌曲时间阶段格式有问题！");
                                }
                            }
                            lyrics.setSongId(songId);
                            lyricsList.add(lyrics);
                        }
                    }
                }
                song.setSongLyricsName(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return userService.updateSong(song,lyricsList);
    }

    /**
     * 管理员对成绩进行打分
     *
     * @param request
     * @param experimentReport
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/adminComment", method = RequestMethod.POST)
    public ServerResponse adminComment(HttpServletRequest request, @RequestBody ExperimentReport experimentReport) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.adminComment(experimentReport);
    }


    /**
     * 用户根据歌曲来上传歌词
     *
     * @param file
     * @param songId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadLyric", method = RequestMethod.POST)
    public ServerResponse uploadLyric(MultipartFile file, Integer songId, HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ") + 1);
//        User u = JwtUtil.unsign(jwt, User.class);
//        if (u == null) {
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        List<Lyrics> lyricsList = new ArrayList<>();
// 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        try {
            File tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, Lyrics.class);
            if (objectList == null) {
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    Lyrics lyrics = (Lyrics) objectList.get(i);
                    String[] lyricDateArray=lyrics.getLyricDate().split(":");
                    for (String lyricDate : lyricDateArray) {
                        try {
                            Integer lyricDateInt=Integer.parseInt(lyricDate);
                        }catch (Exception e){
                            return ServerResponse.createByErrorMsg("上传歌曲时间阶段格式有问题！");
                        }
                    }
                    lyrics.setSongId(songId);
                    lyricsList.add(lyrics);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer status = userService.uploadLyric(lyricsList);
        if (status != 0) {
            return ServerResponse.createBySuccess("上传歌词成功");
        } else {
            return ServerResponse.createByErrorMsg("上传歌词失败");
        }
    }


    /**
     * 下载歌曲上传模板
     * @param response
     */
    @RequestMapping(value = "/uploadSongLyrics",method = RequestMethod.GET)
    public void uploadSongLyrics(HttpServletResponse response){
    ServletOutputStream out = null;
        try {
        out = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        String fileName = "阶段性歌词上传模板";
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
        ExcelUtils.writeExcel(out, Lyrics.class,null);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }



//    /**
//     * U3d请求访问后端接口格式为表单
//     * @param
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/getU3dSongInfo",method = RequestMethod.POST)
//    public ServerResponse getU3dSongInfo(String token,Integer songId){
////        JSONObject jsonObject=new JSONObject(songInfo);
////        String token=jsonObject.getString("token");
////        Integer songId=jsonObject.getInt("songId");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
//        U3DSong u3DSong=userService.getU3dSongInfo(songId);
//        u3DSong.setUsername(u.getUsername());
//        u3DSong.setSongAccompany(netPath+u3DSong.getSongAccompany());
//        u3DSong.setSongPicture(netPath+u3DSong.getSongPicture());
//        u3DSong.setSongOriginal(netPath+u3DSong.getSongOriginal());
//        return ServerResponse.createBySuccess(u3DSong);
//    }

}
